<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/22
 */

namespace App\Models;

use App\Filters\RoleFilter;
use App\Traits\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * 角色模型
 * Class Role
 * @package App\Models
 */
class Role extends Model
{
    use BaseModel, HasFactory;

    /**
     * 指定表名
     */
    protected $table = 'role';

    /**
     * 能批量赋值的属性
     *
     * @var string[]
     */
//    protected $fillable = [];

    /**
     * 不能被批量赋值的属性
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * 数据显示时，设置了敏感信息字段数据中不显示
     *
     * @var array
     */
    protected $hidden = [
        'deleted_at',
        'created_at',
        'updated_at',
        'created_user_id'
    ];

    /**
     * 显示数据时类型转换
     *
     * @var array
     */
    protected $casts = [
    ];

    /**
     * 注册过滤器
     * @param $query
     * @param RoleFilter $filters
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFilter($query, RoleFilter $filters)
    {
        return $filters->apply($query);
    }

    /**
     * 关联“角色-菜单-权限表”
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function roleMenuPermission()
    {
        return $this->hasMany(RoleMenuPermission::class, 'role_id', 'id');
    }

    /**
     * 关联角色栏目权限表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function roleCategory()
    {
        return $this->hasMany(RoleCategory::class, 'role_id', 'id');
    }


    /**
     * 关联管理员角色关系表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userRole() {
        return $this->hasMany(UserRole::class, 'role_id', 'id');
    }

    /**
     * 关联删除角色菜单权限表、管理员角色关系表数据
     */
    protected static function boot()
    {
        parent::boot();
        static::deleted(function ($model) {
            $model->roleMenuPermission()->delete();
            $model->roleCategory()->delete();
            $model->userRole()->delete();
        });
    }
}
